#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>



#define URLSIZE 500 //url size
#define FILESIZE 50000000 //File size 50MB
#define ES 1
#define EN 2
#define ERR -1
#define FARTICLE "article.txt"
#define ROUTE "./output/"


/*****************************GET PARAMS***************************************/

// int get_lang(char *url)
// {
// 	char *es = {"es.wikipedia.org"};
// 	char *en = {"en.wikipedia.org"};

// 	if(strstr(url, es) != NULL)
// 		return ES; 

// 	if(strstr(url, en) != NULL)
// 		return EN;	

// 	return ERR;
// }

/*
 * WIKI URL example: http://en.wikipedia.org/wiki/Castile-La_Mancha
 */
// int get_art(char *url, char **art)
// {
// 	char *init = {"/wiki/"};
	
// 	if ((*art = strstr(url, init)) == NULL)
// 		return -1;

// 	*art = (*art)+strlen(init);

// }

/*****************************DOWNLOAD*****************************************/
int down_article(char *url, char *title)
{
	int pid;

	char *cmd = {"/usr/bin/wget"};
	char *output = {"-O"};
	char *params[5];
	

	params[0] = cmd;
	params[1] = output;
	params[2]; //downloaded file
	params[3] = url;
	params[4] = NULL;

	params[2] = (char *)malloc(sizeof(char) * URLSIZE);
	strcpy(params[2], ROUTE);
	strcat(params[2], title);

	if((mkdir(ROUTE,0777) == -1) && (errno != EEXIST)) {
		perror("No se puede crear el directorio output");
		return -1;
	}

    if ((pid = fork()) == -1){
        perror("fork (wget) error");
        return -1;
    }
    else if (pid == 0) 
    	if (execv(cmd, params) == -1){
    		perror("execv [wget article] error (finding wget in /usr/bin/wget)");
    		return -1;
    	}	

	waitpid(pid, NULL, 0);
	return 0;  
}


int down_es(char *art)
{
	char *url;
	url = (char*)malloc(URLSIZE);
	strcat(url, "es.wikipedia.org/w/index.php?title=");
	strcat(url, art);
	strcat(url, "&action=edit");

	printf("URL %s\n", url);

	if (down_article(url, art) == -1)
		return -1;

	return 0;
}

int down_en(char *art)
{
	char *url;
	url = (char*)malloc(URLSIZE);
	strcat(url, "en.wikipedia.org/w/index.php?title=");
	strcat(url, art);
	strcat(url, "&action=edit");

	printf("ARTURL %s\n",art);
	printf("URL %s\n", url);

	if (down_article(url, art) == -1)
		return -1;

	return 0;
}


/*****************************PARSE********************************************/
// off_t get_fsize ()
// {
// 	struct stat sb;


// 	if (stat (FARTICLE, & sb) != 0) {
// 		return -1;
// 	}
// 	printf("TAMANOO: %lu\n", sb.st_size);

// 	return sb.st_size;
// }


/*
 * Clean article, leave only wiki edit text
 */
int clean_text(char **text)
{
	char *ini;
	char *textini = {"name=\"wpTextbox1\">"};
	char *textfin = {"</textarea>"};
	char *fin;

	ini = strstr(*text, textini);
	ini += strlen(textini);
	fin = strstr(ini, textfin);
	fin[0] = '\0';

	*text = ini; 

	return 0;
}



int write_cleaned(char *contents, char *title, char *file)
{
	int df;
	char *init;//== title ==

	init = (char *)malloc(sizeof(char) * (sizeof(title) + 8));
	strcat(init, "== ");
	strcat(init, title);
	strcat(init, " ==\n");

	if((df = open(file, O_WRONLY|O_TRUNC, 0777)) == -1)
		return -1;	

	if(write(df, init, strlen(init)) == -1)	
		return -1;

	if(write(df, contents, strlen(contents)) == -1)
		return -1;
	close(df);	
}


int get_ed_txt(char *title)
{
	int df;
	struct stat sb;	
	char * contents;
	char * file;

	// if (stat (FARTICLE, & sb) != 0) {
	// 	return -1;
	// }
	//printf("TAMANOO: %d\n", sb.st_size);

	file = (char *)malloc(sizeof(char) * URLSIZE);
	strcpy(file, ROUTE);
	strcat(file, title);

	//READ
	if((df = open(file, O_RDONLY, 0777)) == -1)
		return -1;

	contents = (char *)malloc(sb.st_size + 1);
	
	if(read(df, contents, sb.st_size) == -1)
		return -1;
	close(df);

	//MODIFIED
	clean_text(&contents);
	
	//WRITE
	write_cleaned(contents, title, file);

	return 0;
}


/*
 * ./programa ARTICULO LENGUAJE
 *
 *	ARTICULO = nombre articulo
 * 	LENGUAJE = en, es
 */
int main(int argc, char *argv[])
{

	//TODO change url in param not argv[1]
	//TODO IR indicando en donde falla con un print en el main
	char *url = argv[1];
	char *article;//article name
	char *lang;


	if(argc < 3){
		printf("ERROR:(dowload article) insuficient arguments.\n");
		return -1;
	}

	article = argv[1];
	lang = argv[2];

	//download	
	if(!(strcmp(lang, "es"))){
		if(down_es(article) == -1){
			printf("ERROR:(dowload article) download Spanish article\n");
			return -1;
		}
	}else if(!(strcmp(lang, "en"))){
		if(down_en(article) == -1){
			printf("ERROR:(dowload article) download English article\n");
			return -1;
		}
	}else{
		printf("ERROR:(dowload article) language \n");
		return -1;		
	}

	//get only edit text
	if (get_ed_txt(article) == -1){
		printf("ERROR:(dowload article) edit download text\n");
		return -1;
	}

	return 0;
}